import time
from multiprocessing import Process, Queue, Pool,Manager,Pipe


def producer(queue):
    queue.put(1)
    time.sleep(2)

def consumer(queue):
    time.sleep(2)
    res=queue.get()
    print(res)


def test_queue():
    queue = Queue()
    p = Process(target=producer, args=(queue,))
    c = Process(target=consumer, args=(queue,))
    p.start()
    c.start()
    p.join()
    c.join()

def test_manager_queue():
    pool = Pool(processes=4)
    queue = Manager().Queue(10)
    pool.apply_async(producer, args=(queue,))
    pool.apply_async(consumer, args=(queue,))
    pool.close()
    pool.join()


def producer_pipe(wpipe):
    wpipe.send(1)
    time.sleep(2)

def consumer_pipe(rpipe):
    time.sleep(2)
    res=rpipe.recv()
    print(res)

def test_pipe():
    rpipe,wpipe = Pipe()
    #pipe只能适用于两个进程间通信
    producer=Process(target=producer_pipe,args=(wpipe,))
    consumer=Process(target=consumer_pipe,args=(rpipe,))
    producer.start()
    consumer.start()
    producer.join()
    consumer.join()

def add_data(dict,key,value):
    dict[key]=value
def test_manger_dict():
    dict=Manager().dict()
    p1=Process(target=add_data,args=(dict,"1",1))
    p2=Process(target=add_data,args=(dict,"2",2))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    print(dict)

if __name__ == '__main__':
   test_manger_dict()
